package com.pms.web;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.pms.entity.BaseModel;
import com.pms.entity.IotCardRecharge;
import com.pms.entity.IotCardRechargeHistoricalRecords;
import com.pms.entity.IotWaterPumpGroup;
import com.pms.exception.R;
import com.pms.service.IIotCardRechargeHistoricalRecordsService;
import com.pms.service.IIotCardRechargeService;
import com.pms.service.IIotWaterPumpGroupService;
import com.pms.util.idutil.SnowFlake;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import com.pms.controller.BaseController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("iotCardRecharge")
@Api(value="二汞数据库充值表",description = "二汞数据库充值表")
public class IotCardRechargeController extends BaseController {
    Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    IIotCardRechargeService iotCardRechargeService;
    @Autowired
    IIotWaterPumpGroupService waterPumpGroupService;
    @Autowired
    IIotCardRechargeHistoricalRecordsService iotCardRechargeHistoricalRecordsService;
    /**
     * 数据卡充值
     * @param groupId
     * @param recentlyCurrentBalance
     * @param recentlyName
     * @return
     */
    @PostMapping("/add")
    @ApiOperation(value = "数据卡充值")
    @ApiImplicitParams({
            @ApiImplicitParam(name="groupId",value="水泵组ID",required = true,dataType = "Long",paramType="form"),
            @ApiImplicitParam(name="recentlyCurrentBalance",value="充值总额",required = true,dataType = "BigDecimal",paramType="form"),
            @ApiImplicitParam(name="recentlyName",value="最近充值人",required = true,dataType = "String",paramType="form"),
    })
    public R add(Long groupId, BigDecimal recentlyCurrentBalance, String recentlyName){
        parameterIsNull(groupId,"请填写设备ID");
        parameterIsNull(recentlyCurrentBalance,"充值金额不能为空");
        parameterIsNull(recentlyName,"充值人不能为空");
        //查询测点信息
        IotWaterPumpGroup eq=waterPumpGroupService.selectById(groupId);
        if (eq==null){return  R.error(400,"水泵组信息不存在");}
        if (eq.getDataType()!=2){return  R.error(400,"对不起，该水泵组不属于数据传输方式");}
        IotCardRecharge entity=iotCardRechargeService.selectOne(new EntityWrapper<IotCardRecharge>().eq("group_id",groupId));
        //第一次没有充值记录的时候
        if (entity!=null){
            IotCardRechargeHistoricalRecords records=new IotCardRechargeHistoricalRecords();
            records.setCurrentMoney(entity.getCurrentBalance().add(recentlyCurrentBalance));
            entity.setTotalAmount(entity.getTotalAmount().add(recentlyCurrentBalance));//充值总额
            entity.setCurrentBalance(entity.getCurrentBalance().add(recentlyCurrentBalance));//剩余金额
            entity.setRecentlyCurrentBalance(recentlyCurrentBalance);//最近充值金额
            entity.setRecentlyData(new Date());//最近充值时间
            entity.setRecentlyName(recentlyName);//最近充值人
            entity.setUpdTime(new Date());//操作时间
            entity.setUpdUser(getCurrentUserMap().get("userName"));//操作人
            int y = entity.getCurrentBalance().compareTo(entity.getMonthlyFeeStandard());
            if(entity.getCurrentBalance().signum()==-1){
                entity.setState(3);//欠费
            }else if (y==1||y==0){
                entity.setState(1);//正常
            }else if (y==-1){
                entity.setState(2);//余额不足
            }
            records.setCardId(entity.getCardId());
            records.setRecentlyCurrentBalance(recentlyCurrentBalance);//最近充值金额
            records.setRecentlyData(new Date());//最近充值时间
            records.setRecentlyName(recentlyName);//最近充值人
            records.setGroupId(groupId);//水泵组ID
            records.setCrtTime(new Date());
            records.setCrtUser(getCurrentUserMap().get("userName"));
            iotCardRechargeHistoricalRecordsService.insert(records);
            iotCardRechargeService.updateById(entity);
        }else{
            Long cardId= BaseModel.returnStaticIdLong();;
            entity.setCardId(cardId);
            entity.setTotalAmount(recentlyCurrentBalance);
            entity.setCurrentBalance(recentlyCurrentBalance);//剩余余额
            entity.setRecentlyCurrentBalance(recentlyCurrentBalance);//最近充值金额
            entity.setRecentlyData(new Date());//最近充值时间
            entity.setRecentlyName(recentlyName);//最近充值人
            entity.setGroupName(eq.getParentName());//设备名称
            entity.setPhone(eq.getGroupPhone());//手机卡号
            entity.setState(1);
            entity.setMonthlyFeeStandard(new BigDecimal(0));
            entity.setGroupId(eq.getId());//设备ID
            entity.setCrtTime(new Date());
            entity.setCrtUser(getCurrentUserMap().get("userName"));
            IotCardRechargeHistoricalRecords  records=new IotCardRechargeHistoricalRecords();
            records.setCardId(cardId);
            records.setCurrentMoney(recentlyCurrentBalance);//充值后余额
            records.setRecentlyCurrentBalance(recentlyCurrentBalance);//最近充值金额
            records.setRecentlyData(new Date());//最近充值时间
            records.setRecentlyName(recentlyName);//最近充值人
            records.setGroupId(groupId);//设备ID
            records.setCrtTime(new Date());
            records.setCrtUser(getCurrentUserMap().get("userName"));
            iotCardRechargeHistoricalRecordsService.insert(records);
            iotCardRechargeService.insert(entity);
        }
        return R.ok();
    }


    /**
     * 查询单条数据信息
     * @param cardId
     * @return
     */
    @PostMapping("/findById")
    @ApiOperation(value = "查询单条数据信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name="cardId",value="数据卡充值ID",required = true,dataType = "Long",paramType="form"),
    })
    public R findById(Long cardId){
        parameterIsNull(cardId,"数据卡充值ID不能为空");
        IotCardRecharge cardRecharge= iotCardRechargeService.findById(cardId);
        if (null==cardRecharge){return  R.error(400,"数据卡充值信息不存在");}
        return R.ok().put("data",cardRecharge);
    }


    /**
     * 分页查询数据库充值
     * @return
     */
    @GetMapping(value = "/page")
    @ApiOperation("分页查询数据库充值")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "limit", value = "条数", required = true, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "page", value = "页数", required = true, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "name", value = "", required = false, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "groupId", value = "水泵组ID", required = true, dataType = "userId", paramType = "form"),
    })
    public R page(int limit,int page,String name,String groupId){
        if (StringUtils.isBlank(groupId)){
        return  R.error(400,"水泵组ID不能为空");
        }
        if (limit<1){limit=10;}
        if (page<1){page=1;}
        Page<IotCardRecharge> pages = new Page<>(page,limit);
        Map<String, Object> parameter = new HashMap<>();
        if (StringUtils.isNotBlank(groupId)){
            parameter.put("groupId","ico.group_id in("+groupId+")");
        }
        if (StringUtils.isNotBlank(name)){
            parameter.put("name", "and (ico.group_name like '%"+name+"%' or ico.total_amount like '%"+name+"%'" +
                    "or ico.phone_ like '%"+name+"%'or ico.recently_name like '%"+name+"%')");
                    }
        parameter.put("limit",limit);
        parameter.put("page",(page-1)*limit);
        Page<IotCardRecharge> pageList = iotCardRechargeService.selectByListPage(pages,parameter);
        return  R.ok().put("data",pageList);
    }

    /**
     * 数据卡信息编辑
     * @param cardId
     * @param monthlyFeeStandard
     * @return
     */
    @PostMapping("/update")
    @ApiOperation(value = "数据卡信息编辑")
    @ApiImplicitParams({
            @ApiImplicitParam(name="cardId",value="数据卡充值ID",required = true,dataType = "Long",paramType="form"),
            @ApiImplicitParam(name="monthlyFeeStandard",value="每月收费标准",required = true,dataType = "BigDecimal",paramType="form"),
    })
    public R update(Long cardId,BigDecimal monthlyFeeStandard){
        parameterIsNull(cardId,"请填写数据卡充值ID");
        parameterIsNull(monthlyFeeStandard,"请填写每月收费标准");
        IotCardRecharge entity=iotCardRechargeService.selectById(cardId);
        parameterIsNull(entity,"数据卡充值信息不存在");
        entity.setMonthlyFeeStandard(monthlyFeeStandard);
        entity.setUpdTime(new Date());
        entity.setUpdUser(getCurrentUserMap().get("userName"));
        iotCardRechargeService.updateById(entity);
        return  R.ok();
    }

    /**
     * 查询历史数据
     * @param groupId
     * @return
     */
    @PostMapping("/getHistoricalData")
    @ApiOperation(value = "查询历史数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name="groupId",value="水泵组ID",required = true,dataType = "Long",paramType="form"),
    })
    public R getHistoricalData(Long groupId){
        parameterIsNull(groupId,"请填写水泵组ID");
        List<IotCardRechargeHistoricalRecords> list =iotCardRechargeHistoricalRecordsService.selectListByData(groupId);
        return  R.ok().put("data",list);
    }



}